﻿using System;
using System.Linq;
using System.Text;
using System.Web;
using BaseData;
using BaseData.Exts;
using BaseLib.Helper;
using BaseUtility;

namespace WebUI.Ashx.Acc.Staff
{
    /// <summary>
    /// NewsAdminInfoListSort 的摘要说明
    /// </summary>
    public class NewsAdminInfoListSort : Base, IHttpHandler
    {
        private static readonly AccClass _accId = new AccExts(new GetAccType().Parse(Request.QueryString["url"])).Instances;
        public void ProcessRequest(HttpContext context)
        {
            if (_accId.Id == 0 || string.IsNullOrWhiteSpace(_accId.Name) || _accId.Type == 0) return;
            var act = context.Request.QueryString["act"].ToNull();
            var action = act.Compare("clear") ? "清除" : (act.Compare("add") ? "添加" : "数据");
            MsgErr msg;
            try
            {
                //context.Response.Write("rows:" + context.Request.QueryString["rows"]);
                using (var ctx = new ContextExt())
                {
                    var rows = context.Request.QueryString["rows"].Split(',').Select(Int32.Parse).ToList();
                    var count = rows.Count;
                    foreach (var items in rows.Select(row1 => (ctx.Web_Base_News_Info.Where(q => q.PkId == row1))))
                    {
                        if (items.Any())
                        {
                            var item = items.FirstOrDefault();
                            if (item != null) item.SortId = act.Compare("clear") ? 0 : (act.Compare("add") ? 1 : count);
                        }
                        count--;
                    }
                    ctx.SaveChanges();
                }
                msg = new MsgErr { error = 0, title = "提示信息", type = "info", message = new StringBuilder(action + "排序成功了！"), };
            }
            catch (Exception err)
            {
                msg = new MsgErr { error = 1, title = "错误信息", type = "error", message = new StringBuilder(action + "排序失败了！<br />" + err.Message), };
            }
            context.Response.Write(msg.ObjectsToJson());
            context.Response.ContentType = "text/plain";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}